const PROTO_PATH = "./protos/js_engine.proto";

const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
});
const jsEngineProto = grpc.loadPackageDefinition(packageDefinition).js_engine;

/**
 * Implements the SayHello RPC method.
 */
function execute(call, callback) {
  let result = undefined;
  try {
    const resp = eval(call.request.script);
    result = JSON.stringify({ code: 0, msg: "调用成功", data: result });

    callback(null, { result });
  } catch (error) {
    result = JSON.stringify({ code: 1, msg: "调用失败", data: error });
    callback(null, { result });
  } finally {
    console.log(result);
  }
}
function main() {
  const ip = "0.0.0.0";
  const port = "12345";
  const server_address = `${ip}:${port}`;

  var server = new grpc.Server();
  server.addService(jsEngineProto.JsEngine.service, { execute });
  server.bindAsync(
    server_address,
    grpc.ServerCredentials.createInsecure(),
    () => {
      server.start();
    }
  );

  console.log("Server started: " + server_address);
}

main();
